package ch2;

public class SpeculativeLoadExample {
    private boolean ready = false;
    private int[] data = new int[] {1, 2, 3, 4, 5, 6, 7, 8};

    public void writer() {
        int[] newData = new int[] {1, 2, 3, 4, 5, 6, 7, 8};
        for (int i = 0; i < newData.length; i++) {
            // 该语句包含读内存的操作
            newData[i] = newData[i] - i;
        }
        data = newData;
        // 该语句包含写内存的操作
        ready = true;
    }

    public int reader() {
        int sum = 0;
        int[] snapshot;
        if (ready) {
            snapshot = data;
            for (int i = 0; i < snapshot.length; i++) {
                sum += snapshot[i];
            }
        }
        return sum;
    }

    public static void main(String[] args) {
        SpeculativeLoadExample example = new SpeculativeLoadExample();
        Thread t1 = new Thread() {
            @Override
            public void run() {
                try {
                    Thread.sleep((int) (Math.random() * 1000));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(example.reader());
            }
        };
        Thread t2 = new Thread() {
            @Override
            public void run() {
               example.writer();
            }
        };
        t1.start();
        t2.start();
    }
}
